#coding:utf-8
'''
@author:saintic.com
1.判断网络是否正常
2.判断服务是否健康
3.探测节点心跳信息
'''

import os,socket,subprocess
from GroupInfo import nodes
from GroupInfo import node_services

#把程序输出定位到/dev/null,否则会在程序运行时会在标准输出中显示命令的运行信息
def servercheck(nodes):
    with open(os.devnull,'w') as fnull:
        for node in nodes:
            result = subprocess.call('ping '+node+' -c 2', shell = True, stdout = fnull, stderr = fnull)
            if result:
                print '%s Connected failure' % node
            else:
                print '%s Connected success' % node
    return

#可用于检测程序是否正常，如检测服务和端口
def servicecheck(node_services):
    for ip,port in node_services.items():
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.settimeout(1)
        try:
            sk.connect((ip,port))
            print '%s %d service is UP!' %(ip,port)
        except Exception:
            print '%s %d service is DOWN!'  %(ip,port)
        finally:
            sk.close()
    return

if __name__ == '__main__':
    servercheck(nodes)
    servicecheck(node_services)
